﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.Xml;
using System.ServiceModel;
using UniCT.LinkShareWpf.Interface;


namespace UniCT.LinkShareWpf.CommunicationChannel
{
    public class Server
    {

       ServiceHost _serviceHost;

       public Server (int port,string serviceName)
	    {
    
                    BasicHttpBinding bindingType = new BasicHttpBinding();
                    //bindingType.MaxReceivedMessageSize = 102400;
                    bindingType.MaxReceivedMessageSize = 240000;
                    XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas();
                    //readerQuotas.MaxArrayLength = 100 * 1024;
                    readerQuotas.MaxArrayLength = 400 * 600;
                    bindingType.ReaderQuotas = readerQuotas;
                    _serviceHost = new ServiceHost(typeof(Contract));
                    _serviceHost.AddServiceEndpoint(typeof(IContract), bindingType, createUriServiceBase(port, serviceName));
        
          }

       public void Stop()
        {
            if (_serviceHost != null)
            {
                if (_serviceHost.State == CommunicationState.Opened)
                {
                    _serviceHost.Close();
                    Console.WriteLine("SERVER CHIUSO");
                }
            }

        }

       public void Start()
        {
            try
            {
                _serviceHost.Open();

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }

       internal Uri createUriServiceBase(int port, string serviceName)
        {
            string IPserver = "87.12.210.38";// System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName())[3].ToString();
            //foreach (System.Net.IPAddress IP in System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()))
            //    if (IP.ToString().Split('.')[0] == "151" || IP.ToString().Split('.')[0] == "172" || IP.ToString().Split('.')[0] == "79" || IP.ToString().Split('.')[0] == "87")
            //    {
            //        IPserver = IP.ToString();
            //        break;
            //    }
                UriBuilder ub = new UriBuilder(Uri.UriSchemeHttp, IPserver, port, serviceName);
                Console.WriteLine("SERVER LANCIATO: "+ub.Uri.ToString());
                return ub.Uri;
            
        }



    }
}
